package de.alt.rest.handler;

import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import de.alt.rest.constants.Constants;
import de.alt.rest.constants.DBConstants;
import de.alt.rest.service.RestService;
import de.alt.rest.util.GeneralSuperUtil;

/**
 * The Class IpHanderler.
 */
public class IpHandler {
	
	/** The Constant log. */
	private static final Logger log = Logger.getLogger(RestService.class.getName());

	/** The util. */
	private GeneralSuperUtil util = new GeneralSuperUtil();

	/**
	 * Sets the ip.
	 *
	 * @param id the id
	 * @param ip the ip
	 * @return the entity
	 * @throws MalformedURLException 
	 */
	public Entity setIp(String id, String ip) throws MalformedURLException {
		if (!util.checkRegEx(ip, Constants.IPADDRESS_PATTERN)) {
			log.warning("Invalid Ip");
			throw new MalformedURLException("Invalid Ip");
		}

		Entity address = new GeneralSuperUtil().getById("Address", id);

		if (address != null) {
			address.setProperty(DBConstants.TABLE_ADDRESS_OLD_ADDR, address.getProperty(DBConstants.TABLE_ADDRESS_ADDR));
			address.setProperty(DBConstants.TABLE_ADDRESS_OLD_DATE, address.getProperty(DBConstants.TABLE_ADDRESS_DATE));
		} else {
			address = new Entity(DBConstants.TABLE_ADDRESS, id);
		}

		address.setProperty(DBConstants.TABLE_ADDRESS_ADDR, ip);
		address.setProperty(DBConstants.TABLE_ADDRESS_DATE, Calendar.getInstance(Locale.GERMANY).getTime());
		address.setProperty(DBConstants.TABLE_ADDRESS_MD5, util.md5(ip));
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		datastore.put(address);
		return address;
	}

}
